import json
import aiohttp
from fastapi import APIRouter, Response
from conf.settings import YAML_CONFIG

router = APIRouter()

grafana_config = YAML_CONFIG.get_service_config().custom.grafana
url = grafana_config.get("url", "")
username = grafana_config.get("username", "admin")
password = grafana_config.get("password", "admin")


@router.get("/search")
async def search_grafana(response: Response):
    async with aiohttp.ClientSession() as session:
        cookies = []
        # 1. Login first, then do set-cookies
        async with session.post(f"{url}/login", json={
            "user": username,
            "password": password
        }) as resp:
            for key, value in resp.cookies.items():
                cookies.append(f"{key}={value.value}")
                # response.set_cookie(key=key, value=value.value,
                #                     expires=value['expires'],
                #                     max_age=value['max-age'],
                #                     domain=value['domain'],
                #                     path=value['path'],
                #                     secure=value['secure'],
                #                     httponly=value['httponly'],
                #                     samesite=value['samesite'])
                response.set_cookie(key=key, 
                                    value=value.value)
        # 2. Do grafana search
        async with session.get(f"{url}/api/search", headers={
                "Cookie": "; ".join(cookies)}) as resp:
            return {
                "code": 0,
                "err_msg": "",
                "data": await resp.json()
            }
